package com.smartsoft.fragment;

import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.smartsoft.R;
import com.smartsoft.adapter.CountriesAdapter;
import com.smartsoft.model.ContactData;
import com.smartsoft.service.DataManager;


/**
 * Fragment is used for editing person's info.
 */
public class EditContactFragment extends Fragment {
    /**
     * For debug purposes.
     */
    private static final String TAG = EditContactFragment.class.getName();
    /**
     * Performs required data supplying.
     */
    private DataManager dataManager = DataManager.getInstance();
    /**
     * Callback handler for contact submition.
     */
    private OnEditContactSubmitListener mSubmitionHandler;
    /**
     * Intended for country choosing. Country selection element represented
     * as carousel like list.
     */
    private ListView mCountryCarousel;
    private CountriesAdapter carouselViewAdapter;
    private int currentCountryPosition = CountriesAdapter.CAROUSEL_MIDDLE_POSITION;
    /**
     * Defines possible scrolling direction for carousel list.
     */
    enum ScrollingDirection {UP, DOWN}

    /**
     * Container (activity) should implements this interface in order to be
     * notified when a user submits contact information.
     */
    public interface OnEditContactSubmitListener {
        /**
         * This method will be called on the container in case when
         * user submits contact.
         *
         * @param contactData contains submitted data
         */
        public void onContactSubmitted(ContactData contactData);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (!(activity instanceof OnEditContactSubmitListener)) {
            throw new ClassCastException(activity + " have to implements OnEditContactSubmitListener interface");
        }
        mSubmitionHandler = (OnEditContactSubmitListener) activity;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View editContactFragmentView =  inflater.inflate(R.layout.edit_contact_fragment, container, false);

        final ViewFlipper mAvatarFlipper = (ViewFlipper) editContactFragmentView.findViewById(R.id.avatar_flipper);

        // Populate view flipper with images. Each image creates
        // from XML definition.
        for (Integer drawId : dataManager.getAvatarDrawableIds()) {
            ImageView mAvatarImage = (ImageView) inflater.inflate(R.layout.avatar_view_item, container, false);
            mAvatarImage.setImageResource(drawId);
            mAvatarFlipper.addView(mAvatarImage);
        }

        // Handle "Avatar Forward" and "Avatar Back" actions when user
        // clicks on respective buttons, and perform smooth sliding of images.
        final Button mAvatarForward = (Button) editContactFragmentView.findViewById(R.id.avatar_forward_btn);
        final Button mAvatarBack = (Button) editContactFragmentView.findViewById(R.id.avatar_back_btn);
        mAvatarForward.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mAvatarFlipper.setInAnimation(getActivity(), R.anim.view_transition_in_left);
                mAvatarFlipper.setOutAnimation(getActivity(), R.anim.view_transition_out_left);
                mAvatarFlipper.showNext();
                // if end of list achieved then deactivate forward button
                int stopSlidingAtPosition = dataManager.getAvatarDrawableIds().size() - 1;
                if (mAvatarFlipper.getDisplayedChild() == stopSlidingAtPosition) {
                    mAvatarForward.setEnabled(false);
                }
                if (!mAvatarBack.isEnabled()) {
                    mAvatarBack.setEnabled(true);
                }
            }
        });
        mAvatarBack.setEnabled(false);
        mAvatarBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            mAvatarFlipper.setInAnimation(getActivity(), R.anim.view_transition_in_right);
            mAvatarFlipper.setOutAnimation(getActivity(), R.anim.view_transition_out_right);
            mAvatarFlipper.showPrevious();
            // if end of list achieved then deactivate back button
            int stopSlidingAtPosition = 0;
            if (mAvatarFlipper.getDisplayedChild() == stopSlidingAtPosition) {
                mAvatarBack.setEnabled(false);
            }
            if (!mAvatarForward.isEnabled()) {
                mAvatarForward.setEnabled(true);
            }
            }
        });

        // Sets up countries list (countries items supplied through ListView's custom adapter)
        // for carousel of countries and highlight middle placed country - situated on the
        // middle of the list's visible area.
        mCountryCarousel = (ListView) editContactFragmentView.findViewById(R.id.country_carousel_list);
        carouselViewAdapter = new CountriesAdapter(dataManager.getCountriesData(), getActivity());
        mCountryCarousel.setAdapter(carouselViewAdapter);
        mCountryCarousel.setSelectionFromTop(CountriesAdapter.CAROUSEL_MIDDLE_POSITION, 35);
        mCountryCarousel.setItemChecked(CountriesAdapter.CAROUSEL_MIDDLE_POSITION, true);

        // Add ability of scrolling country items
        Button mPreviousCountry = (Button) editContactFragmentView.findViewById(R.id.prev_country_btn);
        mPreviousCountry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scrollToPosition(ScrollingDirection.DOWN);
            }
        });

        Button mNextCountry = (Button) editContactFragmentView.findViewById(R.id.next_country_btn);
        mNextCountry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scrollToPosition(ScrollingDirection.UP);
            }
        });

        // Handle contact submit operation. Actually submition algorithm will be
        // delegated to the fragment's container.
        Button mSubmitContact = (Button) editContactFragmentView.findViewById(R.id.submit_contact_btn);
        mSubmitContact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ContactData contactData = new ContactData.Builder()
                        .setAvatarDrawableId(mAvatarFlipper.getDisplayedChild())
                        .setName(((EditText) editContactFragmentView.findViewById(R.id.user_name)).getText().toString())
                        .setPhoneNumber(((EditText) editContactFragmentView.findViewById(R.id.phone_number)).getText().toString())
                        .setEmail(((EditText) editContactFragmentView.findViewById(R.id.email)).getText().toString())
                        .setSelectedCountryPosition(currentCountryPosition % dataManager.getCountriesData().size())
                        .build();
                mSubmitionHandler.onContactSubmitted(contactData);
            }
        });
        return editContactFragmentView;
    }

    /**
     * Scroll carousel's content to new position depending of
     * the specified direction.
     *
     * @param scrollDirection   direction of the scrolling Up or Down
     */
    private void scrollToPosition(ScrollingDirection scrollDirection) {
        int goToPosition = scrollDirection == ScrollingDirection.UP ? ++currentCountryPosition : --currentCountryPosition;
        Log.d(TAG, "Go to position " + goToPosition);
        mCountryCarousel.setItemChecked(goToPosition, true);
        mCountryCarousel.setSelectionFromTop(goToPosition, 35);
    }

}